"""
API Routes for Unified Monitoring Service
"""
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import PlainTextResponse
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Dict, Any

from ..services.monitoring_service import MonitoringService
from ..core.exceptions import MonitoringError
from ..main import get_monitoring_service, get_db_session # Will be created

router = APIRouter(prefix="/monitoring", tags=["Monitoring"])

# --- API Endpoints ---

@router.get(
    "/system/metrics",
    response_model=Dict[str, Any],
    status_code=status.HTTP_200_OK
)
async def get_system_metrics(
    service: MonitoringService = Depends(get_monitoring_service)
):
    """
    Get a JSON object with detailed system metrics (CPU, memory, disk).
    """
    try:
        return await service.get_system_metrics()
    except MonitoringError as e:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=str(e)
        )

@router.get(
    "/prometheus/metrics",
    response_class=PlainTextResponse,
    status_code=status.HTTP_200_OK
)
async def get_prometheus_metrics(
    service: MonitoringService = Depends(get_monitoring_service)
):
    """
    Get system metrics formatted for Prometheus scraping.
    """
    try:
        return await service.get_prometheus_formatted_metrics()
    except MonitoringError as e:
        # Prometheus scrapers expect a 5xx error on failure
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=str(e)
        )

@router.get(
    "/alerts/rules",
    response_model=List[Dict[str, Any]],
    status_code=status.HTTP_200_OK
)
async def list_alert_rules(
    service: MonitoringService = Depends(get_monitoring_service),
    session: AsyncSession = Depends(get_db_session)
):
    """
    Get a list of configured alert rules. (Currently mock data).
    """
    try:
        return await service.list_alert_rules(session)
    except MonitoringError as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )
